{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#!/usr/bin/env python\n",
    "# -*- coding:utf-8 -*-\n",
    "#\n",
    "import socket\n",
    "import socketserver\n",
    "import threading\n",
    "import json, types,string\n",
    "import os, time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):\n",
    "    def handle(self):\n",
    "        data = self.request.recv(1024)\n",
    "        jdata = json.loads(data)\n",
    "        print(\"Receive data from '%r'\"% data)\n",
    "        print (\"Receive jdata from '%r'\"% (jdata))\n",
    "    \n",
    "        rec_src = jdata[0]['src']\n",
    "        rec_dst = jdata[0]['dst']\n",
    "        cur_thread = threading.current_thread()\n",
    "        response = [{'thread':cur_thread.name,'src':rec_src,'dst':rec_dst}]\n",
    "        jresp = json.dumps(response)\n",
    "        self.request.sendall(jresp)\n",
    "        rec_cmd = \"proccess \"+rec_src+\" -o \"+rec_dst\n",
    "        print (\"CMD '%r'\" % (rec_cmd))\n",
    "        os.system(rec_cmd)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):\n",
    "    pass\n",
    "# Port 0 means to select an arbitrary unused port\n",
    "\n",
    "HOST, PORT = \"localhost\", 50001\n",
    "socketserver.TCPServer.allow_reuse_address = True\n",
    "server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)\n",
    "ip, port = server.server_address\n",
    "\n",
    "# Start a thread with the server -- that thread will then start one\n",
    "\n",
    "# more thread for each request\n",
    "server_thread = threading.Thread(target=server.serve_forever)\n",
    "# Exit the server thread when the main thread terminates\n",
    "server_thread.daemon = True\n",
    "server_thread.start()\n",
    "print (\"Server loop running in thread:\", server_thread.name)\n",
    "print (\" .... waiting for connection\")\n",
    "# Activate the server; this will keep running until you\n",
    "server.serve_forever()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
